﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.EntityModel;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.InstantTickets
{
    public partial class New : System.Web.UI.Page
    {
        #region Properties

        private InstantTicketBiz _instantTicketBiz;
        private InstantTicketBiz InstantTicketManager
        {
            get { return _instantTicketBiz ?? (_instantTicketBiz = new InstantTicketBiz()); }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        #endregion

        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //txtCode.Text = string.Format("{0:00000}", InstantTicketManager.GetNextCode());
                txtCode.Text = string.Format("{0:00000}", WarrantyCommon.InstantTicketNextCode);
                txtReceivedDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.Now);
                //txtReceivedTime.Text = string.Format("{0:hh:mm}", DateTime.Now);

                // load employees
                var employees = InstantTicketManager.GetEmployees();
                ddlEmployees.DataSource = employees;
                ddlEmployees.DataValueField = "Id";
                ddlEmployees.DataTextField = "Name";
                ddlEmployees.DataBind();

                // load customers
                var groups = CustomerManager.GetAllCustomerGroups();//_repository.CityRepository.GetAllCustomerGroups();
                groups.Insert(0, new CustomerGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });
                ddlCustomerGroups.DataValueField = "Id";
                ddlCustomerGroups.DataTextField = "Name";
                ddlCustomerGroups.DataSource = groups;
                ddlCustomerGroups.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var code = txtCode.Text.Trim();
            if (code.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.CodeIsRequired;
                return;
            }
            DateTime createdDate;
            if (!DateTime.TryParseExact(txtReceivedDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDate))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }
            //var createdDate = new DateTime(tmpCreatedDate.Year, tmpCreatedDate.Month, tmpCreatedDate.Day, tmpCreatedDate.Hour, tmpCreatedDate.Minute, 0); // workaround for SQL 2005

            if (ddlEmployees.SelectedIndex < 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.ReceivedEmployeeRequired;
                return;
            }
            var ticketContent = txtContent.Text.Trim();
            if (ticketContent.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.TicketContentRequired;
                return;
            }
            Customer customer;
            if (rbtNewCustomer.Checked)
            {
                var name = txtName.Text.Trim();
                if (name.Length == 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.NameIsRequired;
                    return;
                }
                customer = new Customer
                               {
                                   Name = name,
                                   Address = txtAddress.Text.Trim(),
                                   Email = txtEmail.Text.Trim(),
                                   Phone = txtPhone.Text.Trim()
                               };
            }
            else
            {
                int customerId;
                if (!int.TryParse(hidCustomerId.Value, out customerId))
                {
                    lblErrorMessage.Text = "CustomerRequired";//Resources.GlobalStrings.NameIsRequired;
                    return;
                }
                if (customerId <= 0)
                {
                    lblErrorMessage.Text = "CustomerRequired";//Resources.GlobalStrings.NameIsRequired;
                    return;
                }
                customer = new Customer { Id = customerId };
            }

            double distance;
            double.TryParse(txtDistance.Text.Trim(), out distance);

            // call create instant ticket biz
            var instantTicket = new InstantTicket
                                    {
                                        Code = code,
                                        CreatedDate = createdDate,
                                        CreatedEmployeeId = int.Parse(ddlEmployees.SelectedValue),
                                        TicketContent = ticketContent,
                                        StatusId = 1, // new
                                        Distance = distance
                                    };
            InstantTicketManager.CreateTicket(instantTicket, customer);
            // check result

            // go to Edit page
            Response.Redirect("Edit.aspx?id=" + instantTicket.Id);
        }

        #endregion
    }
}